package com.naszetatry.map;

import java.io.IOException;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.naszetatry.beans.Edge;
import com.naszetatry.beans.Path;
import com.naszetatry.beans.SearchResult;
import com.naszetatry.beans.Vertex;
import com.naszetatry.controller.MapController;
import com.naszetatry.logic.PathLogic;
import com.naszetatry.logic.SearchResultLogic;
import com.naszetatry.logic.VertexLogic;
/**
 * Serwlet odpowiedzialny za wszystkie operacje zwiazane z mapa. Takie jak:
 * -wyswietlanie
 * -interakcje
 * -wyswietlanie wynikow wyszukiwania
 * @author Maciej Koch
 *
 */
public class Map extends HttpServlet{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		List<Path> paths = PathLogic.loadPaths();
		List<Vertex> vertexes = VertexLogic.loadVertexes();
		List<SearchResult> results;
		List<Edge> resultEdges;
			
		//wyszukiwarka
		if("search".equals(request.getParameter("do"))) {
			
			String startS = request.getParameter("s");
			String endS = request.getParameter("e");
			String pointsS = request.getParameter("p");
			
			//dane do wyszukiwarki
			Vertex start = calculateVector(startS); 
			Vertex end = calculateVector(endS);
			ArrayList<Vertex> points = calculatePoints(pointsS);
			
			//wyniki
			SearchResultLogic srl = SearchResultLogic.createInstance();
			results = srl.searchPaths(start, end, points);
			MapController.setResults(request, results);
		}
		
		
		
		MapController.setVertexes(request, vertexes);	
		MapController.setPaths(request, paths);
		getServletContext().getRequestDispatcher("/jsp/start.jsp").forward(request, response);	
	}
	private Vertex calculateVector(String s) {
		int id = Integer.parseInt(s.substring(1));
		Vertex start = new Vertex();
		start.setId(id);
		return start;
	}
	private ArrayList<Vertex> calculatePoints(String p){
		ArrayList<Vertex> points = new ArrayList<Vertex>();
		//vertexy oddzielamy 'b'
		String[] p2 = p.split("b");
		for(int i = 0 ; i < p2.length ; i ++){
			if(p2[i] != ""){
				Vertex v = new Vertex();
				int id = Integer.parseInt(p2[i].substring(1));
				v.setId(id);
				points.add(v);
			}
		}
		return points;
			
			
			
	}
}

